﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Fibonacci
{
    class Program
    {
        static void Main(string[] args)
        {
            var sw = Stopwatch.StartNew();
            var result = FibonacciGenerator().Take(40).LastOrDefault();
            Console.WriteLine($"{result} {sw.Elapsed}");
            Console.ReadKey();
        }

        // 递归实现
        static int FibonacciRecursion(int n)
        {
            if (n < 2)
            {
                return n;
            }
            else
            {
                return FibonacciRecursion(n - 1) + FibonacciRecursion(n - 2);
            }
        }

        // 尾递归实现
        static int FibonacciTail(int n, int acc1, int acc2)
        {
            if (n < 2)
            {
                return acc1;
            }
            else
            {
                Console.WriteLine($"factorial_tail({n - 1}, {acc2}, {acc1})");
                return FibonacciTail(n - 1, acc2, acc1 + acc2);
            }
        }

        // 生成器实现
        static IEnumerable<int> FibonacciGenerator()
        {
            int current = 1, next = 1;

            while (true)
            {
                yield return current;
                next = current + (current = next);
            }
        }

    }
}
